package com.chushouya.common.util;


import com.chushouya.common.dto.suhuishou.ResponseDTO;
import com.general.framework.core.lang.Dates;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class SuhuishouRequest {
    @Value("${com.suhuishou.baseUrl}")
    private String baseUrl;

    @Value("${com.suhuishou.partnerId}")
    private String partnerId;

    @Value("${com.suhuishou.appKey}")
    private String appKey;

    public <T> ResponseDTO<T> httpRequest(final String path, final String method, final Map<String, Object> params, Class<T> clazz) {
        final String requestUrl = Strings.format("{}{}", baseUrl, path);
        final String timestamp = String.valueOf(Dates.getTimeNow().getTime());
        final String sign = SuhuishouSignUtil.genMd5Sign(params, timestamp, appKey);
        Map<String, String> headers = new HashMap<>();
        headers.put("content-type", "application/json;charset=UTF-8");
        headers.put("shs-partner-id", partnerId);
        headers.put("shs-sign", sign);
        headers.put("shs-timestamp", timestamp);
        String respStr = "";
        log.info("\r\nrequestUrl:{}\r\nparams:{}\r\nheader:{}", requestUrl, params, headers);
        try {
            if (Objects.equals("GET", method)) {
                // GET请求参数需要转换为字符串
                Map<String, String> paramData = new HashMap<>();
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    paramData.put(entry.getKey(), entry.getValue().toString());
                }
                respStr = HttpClientUtil.httpGet(requestUrl,headers, paramData);
            } else if (Objects.equals("POST", method)) {
                respStr = HttpClientUtil.httpPost(requestUrl, headers, Jsons.toJsonString(params));
            }
            log.info("请求成功:{}", respStr);
        } catch (Exception e) {
            log.error("请求发生错误:{}", e.getMessage());
            respStr = "{\"code\":400,\"msg\":\"请求发生错误\",\"data\":null}";
        }

        log.info("respStr:{},{}", requestUrl, respStr);

        return FastJsonUtil.parseResultV2(respStr, clazz);
    }


}
